import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../users/user.entity';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';

const {
  emailExist,
  emailNoExist,
  keyUnValid,
  noPasswordExist,
  loginError,
} = require('../provider/error');
const { sendRegisterEmail } = require('../provider/email');
const { generateNumber, md5, getDate } = require('../utils/tool');

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User) private usersRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  // 注册
  async register(data) {
    const { email, verify_key, password } = data;
    if (!email || !data) return emailNoExist();
    if (!password) return noPasswordExist();
    const result: any = await this.usersRepository.findOne({
      where: { email },
    });
    if (result) {
      if (result.password != '') return emailExist();
      if (result.verify_key != verify_key) return keyUnValid();
      if (result.email == email) {
        await this.usersRepository.update(result.id, {
          password: md5(password),
          verify_key: '',
        });
        return [];
      }
      return emailExist();
    } else {
      return keyUnValid();
    }
    return [];
  }

  // 发送邮箱验证码
  async sendEmail(data) {
    const verify_key = generateNumber();
    if (data.email == '' || !data.email) return emailNoExist();
    const result: any = await this.usersRepository.findOne({
      where: { email: data.email },
    });
    if (result) {
      const { password, email } = result;
      if (password != 0) return emailExist();
      if (email == data.email) {
        await this.usersRepository.update(result.id, {
          verify_key,
        });
        sendRegisterEmail({ ...data, verify_key });
        return [];
      }
    } else {
      await this.usersRepository.save({
        email: data.email,
        username: '',
        password: '',
        open_id: 0,
        avatar:
          '//technique-1251242649.cos.ap-beijing.myqcloud.com/image/jpeg/avatard.jpg',
        config: '',
        verify_key,
        create_time: new Date(),
        updated_time: new Date(),
      });
      sendRegisterEmail({ ...data, verify_key });
      return [];
    }
  }

  // 登陆
  async login(userInfo) {
    const { password, email, username, avatar, config, create_time } = userInfo;
    if (!password) return noPasswordExist();
    if (!email || !userInfo || !email) return emailNoExist();
    const result: any = await this.usersRepository.findOne({
      where: { email },
    });
    if (!result) return loginError();
    if (result.password !== md5(password)) return loginError();
    const token = this.jwtService.sign({ ...result, password: '' });
    return {
      token: 'Bearer ' + token,
      userInfo: {
        username: result.username,
        email: result.email,
        avatar: result.avatar,
        config: result.config,
        create_time: getDate(result.create_time, 0),
      },
    };
  }
}
